<!doctype html>
<script src="../../../../resources/ahem.js"></script>
<script src="../../../../resources/testharness.js"></script>
<script src="../../../../resources/testharnessreport.js"></script>
<style>
body { margin: 0px; }
</style>
<div id="first" style="font: 10px/1 Ahem; width: 4000px; height: 1000px">A long text to test document caretRangeFromPoint. Test scroll, zoom, zoomAndScroll .................................... The End </div>
<script>
// 29 is the character offset in the div text "A long text to test document
// caretRangeFromPoint".
const kExpectedOffset = 29;

const t = async_test();

document.addEventListener('DOMContentLoaded', t.step_func_done(() => {
    const range = document.createRange();
    const node = document.getElementById('first');
    // Set range in the middle of word 'document'.
    range.setStart(node.firstChild, kExpectedOffset);
    range.setEnd(node.firstChild, kExpectedOffset + 1);

    let stepName = '';
    window.addEventListener('click', t.step_func(event => {
        const range = document.caretRangeFromPoint(event.clientX, event.clientY);
        if (!range)
          throw 'caretRangeFromPoint() returns null';
        assert_equals(range.startContainer, node.firstChild,
                      `${stepName}: range.startContainer`);
        assert_equals(range.startOffset, kExpectedOffset,
                      `${stepName}: ${event.clientX} range.startOffset`);
    }));

    function testIt(name, scrollFunction) {
        if (!window.eventSender)
            throw 'This test requires eventSender.';
        stepName = name;
        const shouldScroll = name.startsWith('scroll');
        const scale = shouldScroll ? 0.5 : 1;
        // Note: Style.zoom doesn't affect Range#getClientRects().
        const rect = range.getClientRects()[0];
        const x = rect.left * scale * node.style.zoom;
        const y = (rect.top + rect.height / 2) * node.style.zoom;
        if (shouldScroll)
            scrollTo(x, 0);
        if (window.eventSender) {
            eventSender.leapForward(9999); // reset mouse button state
            eventSender.mouseMoveTo(x, y);
            eventSender.mouseDown();
            eventSender.mouseUp();
        }
        scrollTo(0, 0);
    }

    node.style.zoom = 1.0;
    testIt('base');
    testIt('scroll');

    node.style.zoom = 2.0;
    testIt('zoom');
    testIt('scroll and zoom');

    scrollTo(0, 0);
    node.style.zoom = 1.0;
}));
</script>
